package com.grechur.wanandroidcompose.page


import android.util.Base64
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.ScrollableTabRow
import androidx.compose.material.Tab
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.pager.rememberPagerState
import com.grechur.wanandroidcompose.bean.project.ProjectInfo
import com.grechur.wanandroidcompose.viewmodel.ProjectArticleViewModel
import com.grechur.wanandroidcompose.viewmodel.ProjectViewModel
import com.grechur.wanandroidcompose.widget.ArticlePage
import com.grechur.wanandroidcompose.widget.smartrefresh.NestedScrollMode
import com.grechur.wanandroidcompose.widget.smartrefresh.SmartSwipeRefresh
import com.grechur.wanandroidcompose.widget.smartrefresh.rememberSmartSwipeRefreshState
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.net.URLEncoder
import java.nio.charset.StandardCharsets

@OptIn(ExperimentalPagerApi::class)
@Composable
fun ProjectPage(
    projectViewModel: ProjectViewModel = viewModel(),
    globalNavHostController: NavHostController,
    modifier: Modifier = Modifier,
) {
//    val mProjectTitles by remember {
//        mutableStateOf(projectViewModel.mProjectTitles.value)
//    }
    LaunchedEffect(Unit) {
        projectViewModel.getNetProjectTitles()
    }
    DisposableEffect(Unit) {
        Log.e("zhouzhu", "ProjectPage DisposableEffect")

        onDispose {
            Log.e("zhouzhu", "ProjectPage onDispose")
        }
    }
    val coroutineScope = rememberCoroutineScope()
    var rememberPagerState = rememberPagerState()
    Column(
        modifier = Modifier
            .padding(bottom = 56.dp)
            .navigationBarsPadding()
    ) {
        if (projectViewModel.mProjectResultTitles.isSuccess) {
            projectViewModel.mProjectResultTitles.getOrNull().takeIf { !it.isNullOrEmpty() }
                ?.let { projectTitleList ->
                    ScrollableTabRow(
                        selectedTabIndex = rememberPagerState.currentPage,
                        modifier = Modifier.height(50.dp),
                        edgePadding = 0.dp
                    ) {
                        projectTitleList.forEachIndexed { index, projectInfo ->
                            Tab(
                                selected = index == rememberPagerState.currentPage,
                                onClick = {
                                    coroutineScope.launch {
                                        rememberPagerState.scrollToPage(index)
                                    }
                                },
                                modifier = Modifier
                                    .fillMaxHeight(),

                                ) {
                                projectInfo.name?.apply {
                                    Text(
                                        text = this,
                                        modifier = Modifier.padding(horizontal = 5.dp)
                                    )
                                } ?: Text(text = "this")
                            }
                        }
                    }
                    HorizontalPager(
                        count = projectTitleList.size,
                        state = rememberPagerState
                    ) { page ->
                        Log.e("zhouzhu", "HorizontalPager $page")
                        ProjectArticlePage(
                            globalNavHostController,
                            cid = projectTitleList[page].id.toString(),
                            page = page
                        )
                    }
                }
        } else {
            Text(text = "${projectViewModel.mProjectResultTitles.exceptionOrNull()?.message}")
        }

    }


}

@Composable
fun ProjectArticlePage(globalNavHostController: NavHostController, cid: String, page: Int) {
    val articleViewModel: ProjectArticleViewModel =
        viewModel(ProjectArticleViewModel::class.java, key = cid)
    val refreshState = rememberSmartSwipeRefreshState()
    LaunchedEffect(Unit) {
        articleViewModel.getProjectArticles(1, cid, refreshState)
    }
    LaunchedEffect(refreshState.isRefreshing) {
        Log.e("zhouzhu", "ProjectArticlePage LaunchedEffect:${page} cid:$cid")
        Log.e("zhouzhu", "ProjectArticlePage isRefreshing:${refreshState.isRefreshing}")
        if (refreshState.isRefreshing) {
            articleViewModel.getProjectArticles(1, cid, refreshState)
        }
    }
    LaunchedEffect(refreshState.isLoading) {
        if (refreshState.isLoading) {
            articleViewModel.getProjectArticles(
                articleViewModel.projectArticlesPageIndex.value + 1,
                cid,
                refreshState
            )
        }
    }
    val context = LocalContext.current
    SmartSwipeRefresh(
        state = refreshState,
        onRefresh = {
            refreshState.isRefreshing = true
        },
        onLoadMore = {
            refreshState.isLoading = true
        },
        modifier = Modifier.background(color = Color(0x7FEEEEEE)),
        headerScrollMode = NestedScrollMode.Translate,
        footerScrollMode = NestedScrollMode.Translate,
    ) {
        articleViewModel.projectArticles.let { result ->
            Log.e(
                "zhouzhu",
                "articleViewModel:${articleViewModel.hashCode()} page:${page} cid:$cid result:${result.getOrNull()?.size}"
            )
            if (result.isSuccess) {
                result.getOrDefault(mutableListOf()).takeIf { it.isNotEmpty() }?.let { articles ->
                    LazyColumn() {
                        itemsIndexed(articles) { index, article ->
                            ArticlePage(
                                globalNavHostController = globalNavHostController,
                                article = article,
                                modifier = Modifier
                                    .padding(horizontal = 5.dp)
                                    .clickable {
                                        Toast
                                            .makeText(
                                                context,
                                                "${article.link}",
                                                Toast.LENGTH_SHORT
                                            )
                                            .show()
                                        val link = article.link ?: ""
                                        val encode = Base64.encodeToString(
                                            link.toByteArray(),
                                            Base64.NO_WRAP
                                        )
                                        globalNavHostController.navigate("webView?url=$encode?name=${article.title}")
                                    },
                                index = index,
                                cid = cid
                            )
                        }
                    }
                } ?: Text(text = "")
            } else {
                refreshState.isRefreshing = false
                Toast.makeText(
                    LocalContext.current,
                    "${result.exceptionOrNull()?.message}",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

}

@Preview
@Composable
fun ProjectPagePreview() {
    ProjectPage(globalNavHostController = rememberNavController())
}

